﻿Imports System.Text
Imports System.IO
Imports System.Runtime.InteropServices
Imports EnvDTE
Imports Microsoft.VisualStudio.OLE.Interop
Imports Microsoft.VisualStudio.Shell
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.TextManager.Interop

Namespace Microsoft.VisualStudio.ImageInsertion
	''' <summary>
	''' Provides helper functionality for Visual Studio
	''' </summary>
	Friend Class VisualStudioHelper
        Friend Property ServiceProvider As System.IServiceProvider

		Friend Sub New(ByVal textBuffer As ITextBuffer)
			Me.ServiceProvider = GetServiceProviderFromTextBuffer(textBuffer)
		End Sub

		<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000")>
		Private Shared Function GetServiceProviderFromTextBuffer(ByVal textBuffer As ITextBuffer) As System.IServiceProvider
            Dim objectWithSite = textBuffer.Properties.GetProperty(Of IObjectWithSite)(GetType(IVsTextBuffer))
			If objectWithSite IsNot Nothing Then
                Dim serviceProviderGuid = GetType(Microsoft.VisualStudio.OLE.Interop.IServiceProvider).GUID
                Dim ppServiceProvider = IntPtr.Zero
				' Get the service provider pointer using the Guid of the OleInterop ServiceProvider
				objectWithSite.GetSite(serviceProviderGuid, ppServiceProvider)

				If ppServiceProvider <> IntPtr.Zero Then
					' Create a System.ServiceProvider with the OleInterop ServiceProvider
                    Dim oleInteropServiceProvider = CType(Marshal.GetObjectForIUnknown(ppServiceProvider), OLE.Interop.IServiceProvider)
					Return New ServiceProvider(oleInteropServiceProvider)
				End If
			End If

			Return Nothing
		End Function

		''' <summary>
		''' Adds the file as a child of the active document.
		''' </summary>
		''' <param name="filename"></param>
		Friend Sub AddFileToTheActiveDocument(ByVal filename As String)
            If Not String.IsNullOrEmpty(filename) AndAlso File.Exists(filename) Then
                If Me.ServiceProvider IsNot Nothing Then
                    Dim vs = TryCast(Me.ServiceProvider.GetService(GetType(DTE)), DTE)
                    If vs IsNot Nothing AndAlso vs.ActiveDocument IsNot Nothing Then
                        Dim projectItem = vs.ActiveDocument.ProjectItem.ProjectItems.AddFromFile(filename)
                        If projectItem IsNot Nothing Then
                            Dim buildActionProperty = projectItem.Properties.Item("BuildAction")
                            If buildActionProperty IsNot Nothing Then
                                buildActionProperty.Value = 0
                            End If
                        End If
                    End If
                End If
            End If
		End Sub
	End Class
End Namespace